/////////////////////////////////////////////////////////////////////////////
// Name:        SourceContainer.cpp
// Purpose:     
// Author:      Andrew (cod) Bulavinov
// Modified by: 
// Created:     06/01/2009 17:31:12
// RCS-ID:      
// Copyright:   
// Licence:     
/////////////////////////////////////////////////////////////////////////////

#include "SourceContainer.h"
#include <wx/filefn.h>

bool CheckFormat(const wxString & file, const wxArrayString filters)
{
    for (size_t i = 0; i < filters.size(); ++i) {
        int pos = file.rfind(filters[i]);
        if (pos != -1 && pos == (file.Length() - filters[i].Length())) {
            return true;
        }
    }
    return false;
}

wxDirTraverseResult MediaFinder::OnFile(const wxString& filename)
{
    if (_CurrentEnty.IsEmpty()) {
        _CurrentEnty = _Root;
    }
    if (CheckFormat(filename, _Filters)) {
        
        wxLogTrace(_("Add: \"%s\""), filename.GetData());

        _Entries[_CurrentEnty].Add(filename);
    } else {
        wxLogTrace(_("Skip: \"%s\""), filename.GetData());
    }
    return wxDIR_CONTINUE;
}

wxDirTraverseResult MediaFinder::OnDir(const wxString& dirname)
{
    _CurrentEnty = dirname.SubString(_Root.Length(), dirname.Length());
    
    wxLogTrace(_("Current: \"%s\""), _CurrentEnty.GetData());
    
    if (_Entries.find(_CurrentEnty) != _Entries.end()) {
        _Entries[_CurrentEnty].Clear();
    }
    return wxDIR_CONTINUE;
}


// Scan for new items in source according to filters
//
bool Source::Process()
{
    MediaFinder finder(Path, Filters);
    wxDir       dir(Path);
    
    if (dir.Traverse(finder) != -1) {
        _Processed = true;
    }
    return _Processed;
}

bool Sources::Add(const wxString path, const wxArrayString filters)
{
    if (_SrcList.find(path) == _SrcList.end()) {
        // New source
        Source src(path);
        src.Filters = filters;
        _SrcList[path] = src;
    }
    return true;
}

bool Sources::Update()
{
    bool result = true;
    for (std::map<wxString, Source>::iterator i = _SrcList.begin(); i != _SrcList.end(); ++i) {
        //TODO: logging
        result = result && i->second.Process();
    }
    return result;
}
